// pages/address_administration/address_administration.js
Page({
    /**
     * 页面的初始数据
     */
    data: {
        addressList: []
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {},
    /**
     * 选择地址
     */
    onSelectAddress(e) {
        let pages = getCurrentPages();
        let nowPage = pages[pages.length - 1];
        let prePage = pages[pages.length - 2];
        let index = e.currentTarget.dataset.index;
        // console.log('当前页面栈', pages);
        // console.log('当前页面 ==>', nowPage);
        // console.log('上一个页面 ==>', prePage);
        if(prePage && prePage.__route__ === 'pages/recycle/recycle') {
            // 上一个页面为 一键回收 页
            // 将选择地址存储到本地缓存
            wx.setStorageSync('recycleAddress', this.data.addressList[index]);
            wx.switchTab({
              url: '/pages/recycle/recycle',
            }).then(res => {
                // 跳转成功
                // console.log('to recycle success ==>', res);
            }, err => {
                // 跳转失败
                console.log('to recycle fail ==>', err);
            });
        }else if(prePage && prePage.__route__ === 'pages/place_order/place_order') {
            // 上一个页面为 下单页面
            wx.setStorageSync('recycleAddress', this.data.addressList[index]);
            wx.redirectTo({
              url: '/pages/place_order/place_order',
            }).then(res => {
                // 跳转成功
                console.log('to place_order success ==>', res);
            }, err => {
                // 跳转失败
                console.log('to place_order fail ==>', err);
            });
        }else if(prePage && prePage.__route__ === 'subpkg/goodsBuy/goodsBuy') {
            // 上一个页面为 下单页面
            wx.setStorageSync('idlemallAddress', this.data.addressList[index]);
            wx.redirectTo({
              url: '/subpkg/goodsBuy/goodsBuy',
            }).then(res => {
                // 跳转成功
                console.log('to goodsBuy success ==>', res);
            }, err => {
                // 跳转失败
                console.log('to goodsBuy fail ==>', err);
            });
        }
        // 如果有其它需要选择地址的页面，可在if后加分支
    },
    /**
     * 修改地址
     */
    onEditAddress(e) {
        let index = e.currentTarget.dataset.index;
        // 将要修改数据存储
        wx.setStorageSync('editIndex', index);
        wx.setStorageSync('editAddress', this.data.addressList[index]);
        // console.log('index ==>', index);
        wx.redirectTo({
          url: '/pages/new_address/new_address',
        }).then(res => {
            console.log('address to new res ==> ', res);
        }, err => {
            console.log('address to new err ==> ', err);
        });
    },
    /**
     * 检查是否有修改地址
     */
    checkEditAddress() {
        let editIndex = wx.getStorageSync('editIndex');
        let editAddress = wx.getStorageSync('editAddress');
        let editTarget = 'addressList[' + editIndex + ']';
        if(editIndex !== '') {
            this.setData({
                [editTarget]: editAddress
            });
            wx.removeStorageSync('editIndex');
            wx.removeStorageSync('editAddress');
        }
    },
    /**
     * 改变默认地址
     */
    changeDefaultAddress(e) {
        let index = e.currentTarget.dataset.index;
        let copyAddressList = this.data.addressList;
        for(let i = 0; i < this.data.addressList.length; i++) {
            copyAddressList[i].default = false;
        }
        copyAddressList[index].default = true;
        this.setData({
            addressList: copyAddressList
        });
    },
    /**
     * 跳转到新增地址页面
     */
    onNavTo() {
        wx.redirectTo({
          url: '/pages/new_address/new_address',
        }).then(res => {
            console.log('address to new res ==> ', res);
        }, err => {
            console.log('address to new err ==> ', err);
        });
    },
    /**
     * 删除地址
     */
    deleteAddress(e) {
        let index = e.currentTarget.dataset.index;
        // console.log('deletet index ==> ', index);
        // 显示确认对话框
        wx.showModal({
            title: '提示',
            content: '您确认删除吗？',
            confirmColor: '#42E695',
            cancelColor: '#9E9E9E',
        }).then(res => {
            if (res.confirm) {
                let flag = false;
                // console.log('用户点击确定');
                // 判断删除的地址是否为默认地址
                if(this.data.addressList[index].default) {
                    flag = true;
                }
                let copyAddressList = this.data.addressList;
                copyAddressList.splice(index, 1);
                this.setData({
                    addressList: copyAddressList
                });
                if(flag) {
                    // 默认地址被删除，将当前地址列表第一个设为默认地址
                    if(this.data.addressList.length > 0) {
                        // 如果地址列表不为空
                        this.setData({
                            'addressList[0].default': true
                        });
                    }
                }
                this.$showMsg('删除成功', 'success');
            } else if (res.cancel) {
                // console.log('用户点击取消');
            }
            // console.log('delete yes ==>', res);
        }, err => {
            console.log('delete err ==>', err);
        });
    },
    /**
     * 更新数据库用户地址
     */
    updateAddress() {
        wx.cloud.callFunction({
            name: 'databaseApi',
            data: {
                type: 'updateAddress',
                reqData: this.data.addressList
            }
        }).then(res => {
            // console.log('update address success ==> ', res);
        }, err => {
            console.log('update address err ==> ', err);
        });
    },
    /**
     * 显示消息提示
     * @param {String} msg 消息体
     * @param {String} type 提示类型[loading|success|error|none]
     */
    $showMsg(msg, type) {
        wx.showToast({
          title: msg,
          icon: type
        });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        // 获取用户地址信息
        wx.cloud.callFunction({
            name: 'databaseApi',
            data: {
                type: 'getAddress'
            }
        }).then(res => {
            console.log('getAddress res ==>', res);
            this.setData({
                addressList: res.result.resData
            });
            // 判断有无修改地址
            this.checkEditAddress();
        }, err => {
            console.log('getAddress ==>', err);
        });
    },
    /* 存在问题(不打算修复)
     * 当点击新增或点击时，点击上方的返回图标会跳
     */
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        // 将当前页面修改保存到数据库
        this.updateAddress();
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        // 将当前页面修改保存到数据库
        this.updateAddress();
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})